package com.kxc.service;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.kxc.config.TargetDataSource;
import com.kxc.entity.MoniPoint;

/**
 * 用指定频率读取司南数据库中的库水位实时数据
 * @author jjq
 * @data  2024年1月31日
 * @version
 */
@Service
public class SfDataService {


	@Autowired
	private JdbcTemplate jdbcTemplate;

	SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	// 获取库水位设备单个实时信息
	@TargetDataSource(value = "gnssr")
	public Map<String, Double> getGnssrRealTimeDataInfo(MoniPoint moniPoint, int sfFrequency) {

		// 1、获取当前UTC时间
		DateTime nowTime= DateTime.now(DateTimeZone.UTC);
		// 2、拼接获取当月数据表的表名
		String format = nowTime.toString("yyyyMM");
		String tableName = "data_gnss_"+format;
		// 3、根据监测频率，获取上一次读取时间
		DateTime minusMinutes = nowTime.minusMinutes(sfFrequency);
		String lastTime = minusMinutes.toString("yyyy-,MM-dd HH:mm:ss");
		// 4、根据上次读取时间，获取该时间频率范围内有效的数据
		String sql = "select * from " + tableName +" where time > '" + lastTime + "' and station_name = '" + moniPoint.getDev() + "' order by id desc";
		List<Map<String,Object>> queryFor = jdbcTemplate.queryForList(sql);
		// 5、获取该设备的库水位高程值，构造荷载内容
		Double x = null;
		Double y= null;
		Double h= null;
		Map<String, Double>result=new HashMap<>();

		if(queryFor != null && queryFor.size() > 0) {
			x = Double.valueOf(queryFor.get(0).get("x").toString());
			y = Double.valueOf(queryFor.get(0).get("y").toString());
			h = Double.valueOf(queryFor.get(0).get("h").toString());
		}
		result.put("x", x);
		result.put("y", y);
		result.put("h", h);
		return result;
	}

}
